package net.xdclass.mq;

import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import net.xdclass.model.CouponRecordMessage;
import net.xdclass.service.CouponRecordService;
import org.redisson.api.RedissonClient;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.concurrent.locks.Lock;

@Slf4j
@Component
@RabbitListener(queues = "${mqconfig.coupon_release_queue}")
public class CouponMQListener {

    @Autowired
    private CouponRecordService couponRecordService;

    @Autowired
    private RedissonClient redission;

    @RabbitHandler
    public void releaseCouponRecord(CouponRecordMessage couponRecordMessage, Message message, Channel channel) throws IOException {
        log.info("監听到消息: releaseCouponRecord消息內容: {}", couponRecordMessage);
        long msgTag = message.getMessageProperties().getDeliveryTag();

        Lock lock = redission.getLock("lock:coupon_record_release:" + couponRecordMessage.getTaskId());
        lock.lock();

        boolean flag = couponRecordService.releaseCouponRecord(couponRecordMessage);
        try {
            if (flag) {
                channel.basicAck(msgTag, false);
            } else {
                log.error("釋放优惠券失敗 flag = false: {}", couponRecordMessage);
                channel.basicReject(msgTag, true);
            }
        } catch (IOException e) {
            log.error("釋放优惠券記錄異常: {}, {}", msgTag, e);
            channel.basicReject(msgTag, true);
        } finally {
            lock.unlock();
        }
    }
}
